// for mongodb

function toArray(str) {
  if(str) {
    return str.split(',');
  }
}
 function FindProcessor(find, req){
    this.find = find;
    this.req = req;
    this.sort = function (){
      var sort = toArray(this.req.query.sort);
      if (sort) {
        this.find = this.find.sort(sort.join(' '));
      }
      return this;
    }
    this.select = function(){
      var select = toArray(this.req.query.select);
      if(select) {
        this.find = this.find.select(select.join(' '));
      }
      return this;
    }
    this.paginate = function(){
      var page = this.req.query.page || 0;
      var pageSize = this.req.query.pageSize || 10;

      if (page){
        this.find = this.find.skip(pageSize * page);
      }

      this.find = this.find.limit(pageSize);
      return this;
    }
  }


exports.getCondition = function(req, queryKey){

   var condition = {};
  
  //query condition
  if(queryKey){
    queryKey.forEach(function(key){

      if(typeof key === 'string') {
        var value = req.query[key];
        if (value) {
          condition[key] = value;
        }
      } else {

        var op = key.op;
        var field = key.field;
        var query = key.query || field;
        var queryString = req.query[query];

        switch(op){
          case '$or':
            or(condition, field, queryString);
            break;
          case '$regex':
            regex(condition, field, queryString);
            break;
        }
      }
      
    });
  }
  
  function or(condition,field, queryString){
    if(queryString) {
      var queryArray = toArray(queryString);
      var queryCondition = [];
      queryArray.forEach(function(cond){
        var c = {};
        c[field] = cond;
        queryCondition.push(c);
      });
      condition['$or'] = queryCondition;
    }
  }
  
  function regex(condition,field, queryString){
    if (queryString) {
      condition[field] = {'$regex':queryString};
    }
  }

//keyword
 

  console.log("condition: "+ JSON.stringify(condition));

  return condition;
}

//support sort, select, paginate
exports.wrapFind = function(find, req){
 
  return new FindProcessor(find, req);
}